<template>
  <view
    class="text-[30rpx] w-full flex justify-end items-center"
    :class="{ 'u-light-color': !modelValue }"
    @click="openPopup">
    <text>
      {{ getDictLabel(dictList, modelValue) || (disabled ? '-' : placeholder) }}
    </text>
    <i v-if="!disabled" class="iconfont rightArrow">&#xe60d;</i>
  </view>

  <u-picker
    :show="show"
    :columns="[dictList]"
    :defaultIndex="getDefaultIndex"
    keyName="dictLabel"
    @cancel="closePopup"
    @confirm="confirm"></u-picker>
</template>

<script setup lang="ts">
import { PropType } from 'vue'
import { DictItemTypes, getDictLabel } from '@/api/dict'

const props = defineProps({
  modelValue: {
    type: [Number,String],
    default: ''
  },
  dictList: {
    type: Array as PropType<DictItemTypes[]>,
    default: ()  => {
      return []
    }
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue', 'open'])

// 打开选择弹窗
const show = ref(false)
const openPopup = async () => {
  if(props.disabled) return // 禁用
  show.value = true
  emits('open');
}
const closePopup = () => {
  show.value = false
}

// 回显已选中值
const getDefaultIndex = computed(() => {
  const index = props.dictList.findIndex((v: any) => v.dictValue === props.modelValue)
  return [index < 0 ? 0 : index]
})

// 选中更新绑定值
const confirm = (currentItems: any) => {
  const item = currentItems.value[0];
  emits('update:modelValue', item.dictValue)
  closePopup()
}
</script>

<style lang="scss" scoped></style>
